
#include "UdpServer.hpp"
#include <iostream>

// ./xxxx ip  端口  --服务器的
int main(int argc, char *argv[])
{
    EnableScreen();
    if (argc != 3)
    {
        std::cerr << "Usage : " << argv[0] <<" server-ip-port "<<std::endl;
        exit(0);
    }
    std::string serverip =argv[1];
    uint16_t serverport=std::stoi(argv[2]);

    int sockfd=::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    std::cerr<<"create socket error"<<std::endl;
    

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    server.sin_port=htons(serverport);
    while(1)
    {
        std::string line;
        std::cout<<"Please Enter # ";
        std::getline(std::cin ,line);
        int n=sendto(sockfd,line.c_str(),line.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(n>0)
        {
            struct sockaddr_in temp;
            socklen_t len=sizeof(temp);
            char buffer[1024];
            int m=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr *)&temp,&len);
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<buffer<<std::endl;
            }
            else 
            {
                std::cout<<"recvfrom error"<<std::endl;
                break;
            }
        }
        else 
        {
            std::cout<<"sendto error"<<std::endl;
            break;
        }
    }
    ::close(sockfd);

    return 0;
}